// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using iPanel.DataProvider;
using iPanel.Otlp.Storage;
using OpenTelemetry.Proto.Collector.Resources.V1;

namespace iPanel.Otlp;

public sealed class OtlpResourceService
{
    private readonly ILogger<OtlpResourceService> _logger;
    private readonly TelemetryRepository _telemetryRepository;
    private readonly TelemetryDbContext telemetryDbContext;

    public OtlpResourceService(ILogger<OtlpResourceService> logger, TelemetryRepository telemetryRepository, TelemetryDbContext telemetryDbContext)
    {
        _logger = logger;
        _telemetryRepository = telemetryRepository;
        this.telemetryDbContext = telemetryDbContext;
    }

    public ExportResponse Export(ExportRequest request)
    {
        _telemetryRepository.ResourceChanges(request);
        return new ExportResponse { Output = 1 };
    }

    public Guid GetOrCreateServiceInstanceId(string nodeId)
    {
        var application = telemetryDbContext.Db
           .Queryable<OtlpNodeMapApplicationEntity>()
           .Where(_ => _.NodeId == nodeId)
           .First();

        if (application is null)
            lock (telemetryDbContext.Db)
            {
                application = telemetryDbContext.Db
                       .Queryable<OtlpNodeMapApplicationEntity>()
                       .Where(_ => _.NodeId == nodeId)
                       .First();
                if (application is null)
                {
                    application = new OtlpNodeMapApplicationEntity
                    {
                        Id = Guid.NewGuid(),
                        NodeId = nodeId
                    };
                    telemetryDbContext.Db.Insertable(application).ExecuteCommand();
                }
            }
        return application.Id;
    }
}
